/**
 * Copyright (C) 2010 David Simonek <dafesimonek@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.dafe.partyband.importer.api;

import org.dafe.partyband.db.api.ISong;
import org.dafe.partyband.db.api.ISongResource;
import org.openide.util.Lookup;

/**
 *
 * @author dafe
 */
public final class ResourceTypeUtils {

    private static final IMimeTypeDetector mimeDetector = Lookup.getDefault().lookup(IImporterServices.class).getMimeDetector();

    public static ISongResource getTextWithChords(ISong song) {
        return getPreferredResourceOfType(song, IMimeTypeDetector.ContentType.TEXT_WITH_CHORDS);
    }

    public static ISongResource getAudio(ISong song) {
        return getPreferredResourceOfType(song, IMimeTypeDetector.ContentType.AUDIO);
    }
    
    public static ISongResource getVideo(ISong song) {
        return getPreferredResourceOfType(song, IMimeTypeDetector.ContentType.VIDEO);
    }
    
    public static ISongResource getTablature(ISong song) {
        return getPreferredResourceOfType(song, IMimeTypeDetector.ContentType.TABLATURES_NOTES);
    }
    
    public static ISongResource getPreferredResourceOfType(ISong song, IMimeTypeDetector.ContentType ct) {
        ISongResource lastModifRes = null;
        for (ISongResource songRes : song.getResources()) {
            if (isResourceOfType(songRes, ct)) {
                if (songRes.isPreferred()) {
                    return songRes;
                }
                if (lastModifRes == null || lastModifRes.getLastModified() < songRes.getLastModified()) {
                    lastModifRes = songRes;
                }
            }
        }
        return lastModifRes;
    }
    
    public static boolean isResourceOfType(ISongResource songRes, IMimeTypeDetector.ContentType ct) {
        return ct.equals(mimeDetector.getContentType(songRes.getMimeType()));
    }
    
    public static ISongResource getMp3(ISong song) {
        ISongResource songRes = getAudio(song);
        if (songRes != null) {
            String mime = songRes.getMimeType();
            if (mime.contains("mp3") || mime.contains("mpeg")) {
                return songRes;
            }
        }
        
        return null;
    }
    
    public static boolean hasMp3(ISong song) {
        return getMp3(song) != null;
    }

}
